package com.hcmus.armobile;

import java.util.ArrayList;

import global.global;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

import Server.Post;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.hcmus.arLocation.DetailLocation;

import common.Base64Helper;
import common.Promotion;
import common.Store;
import common.User;
import config.*;

import db.DBHandle;

public class GCMIntentService extends GCMBaseIntentService {

	private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(CommonUtilities.SENDER_ID);
    }
    
    /**
     * Method called on device registered
     **/
    @Override
    protected void onRegistered(Context context, String registrationId) {
    	 Log.e("dang kkys th anh cong voi id : ", registrationId);
    	Log.i(TAG, "Device registered: regId = " + registrationId);
        //displayMessage(context, "Your device registred with GCM");
        //Log.d("NAME", MainActivity.name);
    	
    	global.regID = registrationId;
        ServerUtilities.register(context, "Name", "Email", registrationId);
        String curDate = "23/4/2013";
        User u = new User(1,registrationId,"Name","Email",curDate,0,"");
        boolean re =false;
        if(DBHandle.CreateDBAndTable()==true){
        	re = DBHandle.UserAdd(u);
        }
        if(re==true){
        	global.curUser = u;
        }
    }

    /**
     * Method called on device un registred
     * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
     //   displayMessage(context, getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(context, registrationId);
    }

    /**
     * Method called on Receiving a new message
     * */
    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        
        String message = intent.getExtras().getString("price");
        //message = "test";
       
        message = Base64Helper.B64Decode(message);
        //encoding  byte array into base 64
        
        String arrData[] = message.split(config.char_split_promotion_store_send_gcm);
        
        String promotion = arrData[0];
        String store = arrData[1];
        String image = arrData[2];
        image = Base64Helper.B64Decode(image);
        JSONObject jsonPromotion = Post.ParseString2JsonObject(promotion);
        JSONObject jsonStore= Post.ParseString2JsonObject(store);
        ArrayList<Promotion> lstPromotion = Post.parseJSONPromotion(jsonPromotion);
        ArrayList<Store> lstStore= Post.parseJSONStore(jsonStore);
        //decoding byte array into base64
        
       // byte[] decoded = Base64.decodeBase64(message.getBytes()); 
       // String kq = new String(decoded);
       // message = new String(decoded);

        Promotion curPromotion = lstPromotion.get(0);
        curPromotion.SetListImagePromotion(image);
        Store curStore = lstStore.get(0); 
        
        
      //  System.out.println(new String(decoded, "UTF-8") + "\n");
      
        Log.e("Nhan meesage tu server : ", message);
        message = "congTT Them: " + message;
        //displayMessage(context, message);
        // notifies user
        generateNotification(context, curPromotion, curStore);
    }

    /**
     * Method called on receiving a deleted message
     * */
    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
     //   String message = getString(R.string.gcm_deleted, total);
       // displayMessage(context, message);
        // notifies user
       // generateNotification(context, message);
    }

    /**
     * Method called on Error
     * */
    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "--------------------------Received error: " + errorId);
     //   displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
     //   displayMessage(context, getString(R.string.gcm_recoverable_error,
     //           errorId));
        return super.onRecoverableError(context, errorId);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, Promotion p , Store s) {
    	int icon = R.drawable.ic_launcher; 
        long when = System.currentTimeMillis();
        String message = p.getName();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
        
       // add message to stonge
       // DBHandle.AddPromotion(p);
       // DBHandle.AddStore(s);
        try{
        	DBHandle.AddPromotionPush(p.getId());
        }catch(Exception e){
        	
        }        
        
       // String title = context.getString(R.string.app_name);   
        String title = s.getName();
        Intent notificationIntent = new Intent(context, DetailLocation.class);
        
       // String [] arrData = message.split("@loca@");
        
        notificationIntent.putExtra("promotion_id", p.getId());
        notificationIntent.putExtra("delete_promotion", true);
        notificationIntent.putExtra("location_promotion_to", p.getName());
        notificationIntent.putExtra("location_name_to", s.getName());        
        notificationIntent.putExtra("location_address_to", s.getAddress());   
       
        notificationIntent.putExtra("location_lon_to", s.getLng());
        notificationIntent.putExtra("location_lat_to", s.getLat());
        
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        
        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;
        
        //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
        
        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);            

    }

}
